package com.gopay.bis.spdb.adpay.operation;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.util.Enumeration;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.cipher.utils.LoggerMaskUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.exception.GopayException;

public class CryptoHelper {

	private final static Logger logger = LoggerFactory.getLogger(CryptoHelper.class);

	/**
	 * 解密密钥
	 * 
	 * @author jiangxiangjiao
	 * @param keyValue  Base64密钥字符串
	 * @param keyPath 私钥路径
	 * @param keyPawd  私钥密码
	 * @param
	 * @throws GopayException
	 * 
	 */
	public byte[] decryptKey(String keyValue, String keyPath, String keyPawd, String keyAlias) throws GopayException {

		byte[] b_keyValue = null;
		try {
			// Base64解密
			b_keyValue = Base64.decodeBase64(keyValue);
			PrivateKey privateKey = getPrivateKey(keyPath, keyPawd, keyAlias);
			Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			b_keyValue = cipher.doFinal(b_keyValue);
		} catch (Exception e) {
			logger.error("CipherHelper decryptKey error: ", e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057, "解密密钥异常");
		}
		return b_keyValue;
	}
	
	/**
	 * 将密钥字符串转换成字节数组
	 * @param keyValue
	 */
	public byte[] keyStringToByte(String keyValue){
		return Base64.decodeBase64(keyValue);
	}
	
	/**
	 * 将密钥字节数组转换成字符串
	 * @param keyBytes
	 */
	public String keyByteToString(byte [] keyBytes){
		return Base64.encodeBase64String(keyBytes);
	}

	/**
	 * AES加密
	 * 
	 * @param plainText  待加密明文
	 * @param keyValue Base64加密的密钥
	 * @return
	 */
	public static String encryCipherByAES(String plainText, String keyValue) throws GopayException {
		try {
			// 将密钥进行Base64解密
			byte[] keyBytes = Base64.decodeBase64(keyValue);
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(keyBytes);
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			// AES 加密
			byte [] encryptBytes = cipher.doFinal(plainText.getBytes("GBK"));
			// Base64 加密
			logger.info("加密后字符串-----"+ Base64.encodeBase64String(encryptBytes));
			return Base64.encodeBase64String(encryptBytes);
		} catch (Exception e) {
			logger.error("CipherHelper decryCipherByAES error: ", e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057, "AES解密异常");
		}
	}

	/**
	 * AES解密
	 * 
	 * @param encryMsg 密文字符串
	 * @param keyValue Base64密钥
	 * @return
	 */
	public static String decryCipherByAES(String encryMsg, String keyValue) throws GopayException {
		try {
			// 将密钥Base64解密
			byte[] keyBytes = Base64.decodeBase64(keyValue);
			// Base64 解密
			byte [] encryData = Base64.decodeBase64(encryMsg);
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(keyBytes);
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			// AES 解密
			byte [] decryptBytes = cipher.doFinal(encryData);
			String resultString = new String(decryptBytes,"GBK");
			logger.error("解密 ：GBK --" + LoggerMaskUtils.maskString(resultString));
			return resultString;
		} catch (Exception e) {
			logger.error("CipherHelper decryCipherByAES error: ", e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057, "AES解密异常");
		}

	}

	public static PrivateKey getPrivateKey(String keyPath, String keyPawd, String keyAlias) throws GopayException {
		KeyStore keyStore = getKeyStore(keyPath, keyPawd);
		PrivateKey priKey = null;

		try {
			if (keyPawd != null) {
				char[] cPasswd = keyPawd.toCharArray();
				Enumeration<String> aliasenum = keyStore.aliases();
				while (aliasenum.hasMoreElements()) {
					keyAlias = (String) aliasenum.nextElement();
					priKey = (PrivateKey) keyStore.getKey(keyAlias, cPasswd);
					if (priKey != null)
						break;
				}
			}
		} catch (Exception e) {
			logger.error("CipherHelper getPrivateKey error: ", e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057, "获取私钥异常");
		}
		return priKey;
	}

	public static KeyStore getKeyStore(String keyPath, String keyPawd) {
		KeyStore keyStore = null;
		FileInputStream inputStream = null;

		try {
			inputStream = new FileInputStream(new File(keyPath));
			keyStore = KeyStore.getInstance("PKCS12");
			keyStore.load(inputStream, keyPawd.toCharArray());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return keyStore;
	}

}
